/**
 * 笔记管理路由
 * Notes Management Routes
 */

const express = require('express');
const { body, validationResult, query } = require('express-validator');
const router = express.Router();

const Note = require('../database/models/Note');
const logger = require('../utils/logger');

/**
 * 获取笔记列表
 * GET /api/notes
 */
router.get('/', 
  [
    query('page')
      .optional()
      .isInt({ min: 1 })
      .withMessage('页码必须是正整数 / Page must be a positive integer'),
    query('pageSize')
      .optional()
      .isInt({ min: 1, max: 100 })
      .withMessage('每页数量必须在1-100之间 / Page size must be between 1-100'),
    query('search')
      .optional()
      .isLength({ max: 200 })
      .withMessage('搜索关键词不能超过200字符 / Search keyword cannot exceed 200 characters'),
    query('onlyFavorites')
      .optional()
      .isBoolean()
      .withMessage('收藏筛选必须是布尔值 / Favorites filter must be boolean'),
    query('includeDeleted')
      .optional()
      .isBoolean()
      .withMessage('包含已删除必须是布尔值 / Include deleted must be boolean')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { id: userId } = req.user;
      const {
        page = 1,
        pageSize = 20,
        search = '',
        onlyFavorites = false,
        includeDeleted = false
      } = req.query;

      let result;

      if (search) {
        // 搜索笔记
        result = await Note.searchNotes(userId, search, {
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        });
      } else {
        // 获取笔记列表
        result = await Note.getUserNotes(userId, {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          onlyFavorites: onlyFavorites === 'true',
          includeDeleted: includeDeleted === 'true'
        });
      }

      res.json({
        success: true,
        message: '获取笔记列表成功 / Get notes list successful',
        ...result
      });

    } catch (error) {
      logger.error('获取笔记列表失败 / Failed to get notes list', {
        userId: req.user?.id,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 获取单个笔记
 * GET /api/notes/:id
 */
router.get('/:id', async (req, res, next) => {
  try {
    const { id: noteId } = req.params;
    const { id: userId } = req.user;

    // 验证笔记ID
    if (!noteId || isNaN(noteId)) {
      return res.status(400).json({
        success: false,
        message: '无效的笔记ID / Invalid note ID'
      });
    }

    const note = await Note.getNoteDetail(parseInt(noteId), userId);

    if (!note) {
      return res.status(404).json({
        success: false,
        message: '笔记不存在 / Note not found'
      });
    }

    res.json({
      success: true,
      message: '获取笔记成功 / Get note successful',
      note
    });

  } catch (error) {
    logger.error('获取笔记失败 / Failed to get note', {
      userId: req.user?.id,
      noteId: req.params.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 创建笔记
 * POST /api/notes
 */
router.post('/',
  [
    body('title')
      .optional()
      .isLength({ max: 200 })
      .withMessage('标题不能超过200字符 / Title cannot exceed 200 characters'),
    body('content')
      .optional()
      .isLength({ max: 1000000 })
      .withMessage('内容不能超过1MB / Content cannot exceed 1MB'),
    body('content_type')
      .optional()
      .isIn(['html', 'markdown', 'plain'])
      .withMessage('内容类型必须是html、markdown或plain / Content type must be html, markdown or plain'),
    body('tags')
      .optional()
      .isArray()
      .withMessage('标签必须是数组 / Tags must be an array'),
    body('tags.*')
      .optional()
      .isLength({ min: 1, max: 50 })
      .withMessage('标签长度必须在1-50字符之间 / Tag length must be between 1-50 characters'),
    body('is_favorite')
      .optional()
      .isBoolean()
      .withMessage('收藏状态必须是布尔值 / Favorite status must be boolean')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { id: userId } = req.user;
      const { title, content, content_type, tags, is_favorite } = req.body;

      // 创建笔记数据
      const noteData = {
        title: title || '无标题笔记 / Untitled Note',
        content: content || '',
        content_type: content_type || 'html',
        tags: tags || [],
        is_favorite: is_favorite || false
      };

      const note = await Note.createNote(userId, noteData);

      logger.info('笔记创建成功 / Note created successfully', {
        userId,
        noteId: note.id,
        title: note.title
      });

      res.status(201).json({
        success: true,
        message: '笔记创建成功 / Note created successfully',
        note
      });

    } catch (error) {
      logger.error('创建笔记失败 / Failed to create note', {
        userId: req.user?.id,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 更新笔记
 * PUT /api/notes/:id
 */
router.put('/:id',
  [
    body('title')
      .optional()
      .isLength({ max: 200 })
      .withMessage('标题不能超过200字符 / Title cannot exceed 200 characters'),
    body('content')
      .optional()
      .isLength({ max: 1000000 })
      .withMessage('内容不能超过1MB / Content cannot exceed 1MB'),
    body('content_type')
      .optional()
      .isIn(['html', 'markdown', 'plain'])
      .withMessage('内容类型必须是html、markdown或plain / Content type must be html, markdown or plain'),
    body('tags')
      .optional()
      .isArray()
      .withMessage('标签必须是数组 / Tags must be an array'),
    body('tags.*')
      .optional()
      .isLength({ min: 1, max: 50 })
      .withMessage('标签长度必须在1-50字符之间 / Tag length must be between 1-50 characters'),
    body('is_favorite')
      .optional()
      .isBoolean()
      .withMessage('收藏状态必须是布尔值 / Favorite status must be boolean')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { id: noteId } = req.params;
      const { id: userId } = req.user;

      // 验证笔记ID
      if (!noteId || isNaN(noteId)) {
        return res.status(400).json({
          success: false,
          message: '无效的笔记ID / Invalid note ID'
        });
      }

      const updateData = {};
      const { title, content, content_type, tags, is_favorite } = req.body;

      // 只更新提供的字段
      if (title !== undefined) updateData.title = title;
      if (content !== undefined) updateData.content = content;
      if (content_type !== undefined) updateData.content_type = content_type;
      if (tags !== undefined) updateData.tags = tags;
      if (is_favorite !== undefined) updateData.is_favorite = is_favorite;

      if (Object.keys(updateData).length === 0) {
        return res.status(400).json({
          success: false,
          message: '没有提供要更新的数据 / No data provided for update'
        });
      }

      const updatedNote = await Note.updateNote(parseInt(noteId), userId, updateData);

      if (!updatedNote) {
        return res.status(404).json({
          success: false,
          message: '笔记不存在或无权限 / Note not found or no permission'
        });
      }

      res.json({
        success: true,
        message: '笔记更新成功 / Note updated successfully',
        note: updatedNote
      });

    } catch (error) {
      logger.error('更新笔记失败 / Failed to update note', {
        userId: req.user?.id,
        noteId: req.params.id,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 删除笔记（软删除）
 * DELETE /api/notes/:id
 */
router.delete('/:id', async (req, res, next) => {
  try {
    const { id: noteId } = req.params;
    const { id: userId } = req.user;

    // 验证笔记ID
    if (!noteId || isNaN(noteId)) {
      return res.status(400).json({
        success: false,
        message: '无效的笔记ID / Invalid note ID'
      });
    }

    const deleted = await Note.deleteNote(parseInt(noteId), userId);

    if (!deleted) {
      return res.status(404).json({
        success: false,
        message: '笔记不存在或无权限 / Note not found or no permission'
      });
    }

    res.json({
      success: true,
      message: '笔记删除成功 / Note deleted successfully'
    });

  } catch (error) {
    logger.error('删除笔记失败 / Failed to delete note', {
      userId: req.user?.id,
      noteId: req.params.id,
      error: error.message
    });
    next(error);
  }
});/*
*
 * 恢复已删除的笔记
 * POST /api/notes/:id/restore
 */
router.post('/:id/restore', async (req, res, next) => {
  try {
    const { id: noteId } = req.params;
    const { id: userId } = req.user;

    // 验证笔记ID
    if (!noteId || isNaN(noteId)) {
      return res.status(400).json({
        success: false,
        message: '无效的笔记ID / Invalid note ID'
      });
    }

    const restored = await Note.restoreNote(parseInt(noteId), userId);

    if (!restored) {
      return res.status(404).json({
        success: false,
        message: '已删除的笔记不存在 / Deleted note not found'
      });
    }

    res.json({
      success: true,
      message: '笔记恢复成功 / Note restored successfully'
    });

  } catch (error) {
    logger.error('恢复笔记失败 / Failed to restore note', {
      userId: req.user?.id,
      noteId: req.params.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 永久删除笔记
 * DELETE /api/notes/:id/permanent
 */
router.delete('/:id/permanent', async (req, res, next) => {
  try {
    const { id: noteId } = req.params;
    const { id: userId } = req.user;

    // 验证笔记ID
    if (!noteId || isNaN(noteId)) {
      return res.status(400).json({
        success: false,
        message: '无效的笔记ID / Invalid note ID'
      });
    }

    const deleted = await Note.permanentDeleteNote(parseInt(noteId), userId);

    if (!deleted) {
      return res.status(404).json({
        success: false,
        message: '笔记不存在或无权限 / Note not found or no permission'
      });
    }

    res.json({
      success: true,
      message: '笔记永久删除成功 / Note permanently deleted successfully'
    });

  } catch (error) {
    logger.error('永久删除笔记失败 / Failed to permanently delete note', {
      userId: req.user?.id,
      noteId: req.params.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 获取用户标签列表
 * GET /api/notes/tags/list
 */
router.get('/tags/list', async (req, res, next) => {
  try {
    const { id: userId } = req.user;

    const tags = await Note.getUserTags(userId);

    res.json({
      success: true,
      message: '获取标签列表成功 / Get tags list successful',
      tags
    });

  } catch (error) {
    logger.error('获取标签列表失败 / Failed to get tags list', {
      userId: req.user?.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 根据标签获取笔记
 * GET /api/notes/tags/:tag
 */
router.get('/tags/:tag',
  [
    query('page')
      .optional()
      .isInt({ min: 1 })
      .withMessage('页码必须是正整数 / Page must be a positive integer'),
    query('pageSize')
      .optional()
      .isInt({ min: 1, max: 100 })
      .withMessage('每页数量必须在1-100之间 / Page size must be between 1-100')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { tag } = req.params;
      const { id: userId } = req.user;
      const { page = 1, pageSize = 20 } = req.query;

      if (!tag) {
        return res.status(400).json({
          success: false,
          message: '标签不能为空 / Tag cannot be empty'
        });
      }

      const result = await Note.getNotesByTag(userId, tag, {
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      });

      res.json({
        success: true,
        message: '根据标签获取笔记成功 / Get notes by tag successful',
        tag,
        ...result
      });

    } catch (error) {
      logger.error('根据标签获取笔记失败 / Failed to get notes by tag', {
        userId: req.user?.id,
        tag: req.params.tag,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 获取用户笔记统计
 * GET /api/notes/stats
 */
router.get('/stats/summary', async (req, res, next) => {
  try {
    const { id: userId } = req.user;

    const stats = await Note.getUserNoteStats(userId);

    res.json({
      success: true,
      message: '获取笔记统计成功 / Get notes statistics successful',
      stats
    });

  } catch (error) {
    logger.error('获取笔记统计失败 / Failed to get notes statistics', {
      userId: req.user?.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 获取最近更新的笔记
 * GET /api/notes/recent
 */
router.get('/recent/list',
  [
    query('limit')
      .optional()
      .isInt({ min: 1, max: 50 })
      .withMessage('限制数量必须在1-50之间 / Limit must be between 1-50')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { id: userId } = req.user;
      const { limit = 10 } = req.query;

      const notes = await Note.getRecentNotes(userId, parseInt(limit));

      res.json({
        success: true,
        message: '获取最近笔记成功 / Get recent notes successful',
        notes
      });

    } catch (error) {
      logger.error('获取最近笔记失败 / Failed to get recent notes', {
        userId: req.user?.id,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 批量操作笔记
 * POST /api/notes/batch
 */
router.post('/batch',
  [
    body('action')
      .isIn(['delete', 'restore', 'favorite', 'unfavorite'])
      .withMessage('操作类型必须是delete、restore、favorite或unfavorite / Action must be delete, restore, favorite or unfavorite'),
    body('noteIds')
      .isArray({ min: 1 })
      .withMessage('笔记ID列表不能为空 / Note IDs list cannot be empty'),
    body('noteIds.*')
      .isInt({ min: 1 })
      .withMessage('笔记ID必须是正整数 / Note ID must be positive integer')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { action, noteIds } = req.body;
      const { id: userId } = req.user;

      const results = {
        success: 0,
        failed: 0,
        errors: []
      };

      for (const noteId of noteIds) {
        try {
          let result = false;
          
          switch (action) {
            case 'delete':
              result = await Note.deleteNote(noteId, userId);
              break;
            case 'restore':
              result = await Note.restoreNote(noteId, userId);
              break;
            case 'favorite':
              result = await Note.updateNote(noteId, userId, { is_favorite: true });
              break;
            case 'unfavorite':
              result = await Note.updateNote(noteId, userId, { is_favorite: false });
              break;
          }

          if (result) {
            results.success++;
          } else {
            results.failed++;
            results.errors.push(`笔记ID ${noteId} 操作失败 / Note ID ${noteId} operation failed`);
          }
        } catch (error) {
          results.failed++;
          results.errors.push(`笔记ID ${noteId} 错误: ${error.message} / Note ID ${noteId} error: ${error.message}`);
        }
      }

      logger.info('批量操作笔记完成 / Batch notes operation completed', {
        userId,
        action,
        noteIds: noteIds.length,
        success: results.success,
        failed: results.failed
      });

      res.json({
        success: true,
        message: `批量${action}操作完成 / Batch ${action} operation completed`,
        results
      });

    } catch (error) {
      logger.error('批量操作笔记失败 / Failed to batch operate notes', {
        userId: req.user?.id,
        error: error.message
      });
      next(error);
    }
  }
);

module.exports = router;/**
 
* 搜索相关路由
 */
const searchService = require('../services/SearchService');

/**
 * 全局搜索
 * GET /api/notes/search/global
 */
router.get('/search/global',
  [
    query('q')
      .notEmpty()
      .isLength({ min: 1, max: 200 })
      .withMessage('搜索关键词长度必须在1-200字符之间 / Search keyword length must be between 1-200 characters'),
    query('type')
      .optional()
      .isIn(['all', 'notes', 'files'])
      .withMessage('搜索类型必须是all、notes或files / Search type must be all, notes or files'),
    query('sortBy')
      .optional()
      .isIn(['relevance', 'date', 'title'])
      .withMessage('排序方式必须是relevance、date或title / Sort by must be relevance, date or title'),
    query('page')
      .optional()
      .isInt({ min: 1 })
      .withMessage('页码必须是正整数 / Page must be a positive integer'),
    query('pageSize')
      .optional()
      .isInt({ min: 1, max: 100 })
      .withMessage('每页数量必须在1-100之间 / Page size must be between 1-100')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { id: userId } = req.user;
      const {
        q: keyword,
        type = 'all',
        sortBy = 'relevance',
        page = 1,
        pageSize = 20
      } = req.query;

      const results = await searchService.globalSearch(userId, keyword, {
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        type,
        sortBy
      });

      res.json({
        success: true,
        message: '全局搜索成功 / Global search successful',
        keyword,
        ...results
      });

    } catch (error) {
      logger.error('全局搜索失败 / Global search failed', {
        userId: req.user?.id,
        keyword: req.query.q,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 高级搜索
 * POST /api/notes/search/advanced
 */
router.post('/search/advanced',
  [
    body('keyword')
      .optional()
      .isLength({ max: 200 })
      .withMessage('关键词不能超过200字符 / Keyword cannot exceed 200 characters'),
    body('title')
      .optional()
      .isLength({ max: 200 })
      .withMessage('标题不能超过200字符 / Title cannot exceed 200 characters'),
    body('content')
      .optional()
      .isLength({ max: 500 })
      .withMessage('内容不能超过500字符 / Content cannot exceed 500 characters'),
    body('tags')
      .optional()
      .isArray()
      .withMessage('标签必须是数组 / Tags must be an array'),
    body('contentType')
      .optional()
      .isIn(['html', 'markdown', 'plain'])
      .withMessage('内容类型必须是html、markdown或plain / Content type must be html, markdown or plain'),
    body('onlyFavorites')
      .optional()
      .isBoolean()
      .withMessage('收藏筛选必须是布尔值 / Favorites filter must be boolean'),
    body('sortBy')
      .optional()
      .isIn(['relevance', 'date', 'title', 'created_at'])
      .withMessage('排序方式无效 / Invalid sort by option'),
    body('page')
      .optional()
      .isInt({ min: 1 })
      .withMessage('页码必须是正整数 / Page must be a positive integer'),
    body('pageSize')
      .optional()
      .isInt({ min: 1, max: 100 })
      .withMessage('每页数量必须在1-100之间 / Page size must be between 1-100')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { id: userId } = req.user;
      const searchParams = req.body;

      const results = await searchService.advancedSearch(userId, searchParams);

      res.json({
        success: true,
        message: '高级搜索成功 / Advanced search successful',
        ...results
      });

    } catch (error) {
      logger.error('高级搜索失败 / Advanced search failed', {
        userId: req.user?.id,
        searchParams: req.body,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 搜索建议
 * GET /api/notes/search/suggestions
 */
router.get('/search/suggestions',
  [
    query('q')
      .notEmpty()
      .isLength({ min: 1, max: 100 })
      .withMessage('搜索关键词长度必须在1-100字符之间 / Search keyword length must be between 1-100 characters'),
    query('limit')
      .optional()
      .isInt({ min: 1, max: 20 })
      .withMessage('限制数量必须在1-20之间 / Limit must be between 1-20')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { id: userId } = req.user;
      const { q: keyword, limit = 10 } = req.query;

      const suggestions = await searchService.getSearchSuggestions(userId, keyword, parseInt(limit));

      res.json({
        success: true,
        message: '获取搜索建议成功 / Get search suggestions successful',
        keyword,
        suggestions
      });

    } catch (error) {
      logger.error('获取搜索建议失败 / Get search suggestions failed', {
        userId: req.user?.id,
        keyword: req.query.q,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 搜索历史
 * GET /api/notes/search/history
 */
router.get('/search/history',
  [
    query('limit')
      .optional()
      .isInt({ min: 1, max: 50 })
      .withMessage('限制数量必须在1-50之间 / Limit must be between 1-50')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { id: userId } = req.user;
      const { limit = 20 } = req.query;

      const history = searchService.getSearchHistory(userId, parseInt(limit));

      res.json({
        success: true,
        message: '获取搜索历史成功 / Get search history successful',
        history
      });

    } catch (error) {
      logger.error('获取搜索历史失败 / Get search history failed', {
        userId: req.user?.id,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 清除搜索历史
 * DELETE /api/notes/search/history
 */
router.delete('/search/history', async (req, res, next) => {
  try {
    const { id: userId } = req.user;

    searchService.clearSearchHistory(userId);

    res.json({
      success: true,
      message: '搜索历史清除成功 / Search history cleared successfully'
    });

  } catch (error) {
    logger.error('清除搜索历史失败 / Clear search history failed', {
      userId: req.user?.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 热门搜索
 * GET /api/notes/search/popular
 */
router.get('/search/popular',
  [
    query('limit')
      .optional()
      .isInt({ min: 1, max: 20 })
      .withMessage('限制数量必须在1-20之间 / Limit must be between 1-20')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { limit = 10 } = req.query;

      const popularSearches = searchService.getPopularSearches(parseInt(limit));

      res.json({
        success: true,
        message: '获取热门搜索成功 / Get popular searches successful',
        popularSearches
      });

    } catch (error) {
      logger.error('获取热门搜索失败 / Get popular searches failed', {
        userId: req.user?.id,
        error: error.message
      });
      next(error);
    }
  }
);

/**
 * 搜索统计
 * GET /api/notes/search/stats
 */
router.get('/search/stats', async (req, res, next) => {
  try {
    const { id: userId } = req.user;

    const stats = searchService.getSearchStats(userId);

    res.json({
      success: true,
      message: '获取搜索统计成功 / Get search statistics successful',
      stats
    });

  } catch (error) {
    logger.error('获取搜索统计失败 / Get search statistics failed', {
      userId: req.user?.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 获取用户笔记统计
 * GET /api/notes/stats/summary
 */
router.get('/stats/summary', async (req, res, next) => {
  try {
    const { id: userId } = req.user;

    const stats = await Note.getUserNoteStats(userId);

    res.json({
      success: true,
      message: '获取笔记统计成功 / Get notes statistics successful',
      stats
    });

  } catch (error) {
    logger.error('获取笔记统计失败 / Failed to get notes statistics', {
      userId: req.user?.id,
      error: error.message
    });
    next(error);
  }
});

/**
 * 获取最近更新的笔记
 * GET /api/notes/recent/list
 */
router.get('/recent/list',
  [
    query('limit')
      .optional()
      .isInt({ min: 1, max: 50 })
      .withMessage('限制数量必须在1-50之间 / Limit must be between 1-50')
  ],
  async (req, res, next) => {
    try {
      // 验证输入
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败 / Input validation failed',
          errors: errors.array()
        });
      }

      const { id: userId } = req.user;
      const { limit = 10 } = req.query;

      const notes = await Note.getRecentNotes(userId, parseInt(limit));

      res.json({
        success: true,
        message: '获取最近笔记成功 / Get recent notes successful',
        notes
      });

    } catch (error) {
      logger.error('获取最近笔记失败 / Failed to get recent notes', {
        userId: req.user?.id,
        error: error.message
      });
      next(error);
    }
  }
);
m
odule.exports = router;